package top.xia17.plugins.fast.auth.register;

import top.xia17.plugins.fast.common.exceptions.BadConfigException;
import top.xia17.plugins.fast.common.exceptions.BadRequestException;
import top.xia17.plugins.fast.common.spring.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.xia17.plugins.fast.auth.autoconfiguraion.AuthProperties;

import java.util.*;

/**
 * 注册验证码发射器管理类
 *
 * @author xia17
 */
@Slf4j
@Component
public class RegisterCodeLauncherManager {

    public RegisterCodeLauncherManager(AuthProperties authProperties) {
        this.registerProperties = authProperties.getRegister();
    }

    private final RegisterProperties registerProperties;

    /** 存储已经初始化好的发射器 */
    private final Map<String, RegisterCodeLauncher> launcherMap = new HashMap<>(6);


    /**
     * 从容器中获取注册验证码发射器
     * @param id /
     * @return /
     */
    public Optional<RegisterCodeLauncher> obtain(String id){
        RegisterCodeLauncher launcher = launcherMap.get(id);
        if (launcher == null){
            synchronized (this){
                launcher = launcherMap.get(id);
                if (launcher != null){
                    return Optional.of(launcher);
                }
                // 从容器中获取
                Collection<RegisterCodeLauncher> beans = SpringContextHolder.getBeans(RegisterCodeLauncher.class);
                Optional<RegisterCodeLauncher> optional = beans.stream().filter(e -> e.getId().equals(id)).findFirst();
                // 初始化注册验证码发射器
                optional.ifPresent(this::initLauncher);
                return optional;
            }
        }
        return Optional.of(launcher);
    }

    /**
     * 从容器中获取注册验证码发射器,如果不存在抛出异常
     *
     * @param id /
     * @return /
     */
    public RegisterCodeLauncher obtainOrElseThrow(String id) {
        return obtain(id).orElseThrow(() -> new BadConfigException("没有找到id为" + id + "的注册验证码发射器"));
    }

    /**
     * 获取支持的注册验证码发射器
     *
     * @param id /
     * @return /
     */
    public RegisterCodeLauncher obtainSupport(String id) {
        List<String> list = Arrays.asList(registerProperties.getSupportRegisterCodeLauncher());
        if (!list.contains(id)) {
            throw new BadRequestException("暂不支持该注册方式！");
        }
        return obtainOrElseThrow(id);
    }

    /**
     * 初始化注册验证码发射器
     *
     * @param registerCodeLauncher 注册验证码发射器
     */
    private void initLauncher(RegisterCodeLauncher registerCodeLauncher) {
        Map<String, String> properties = registerProperties.getRegisterCodeLauncherProperties().get(registerCodeLauncher.getId());
        registerCodeLauncher.setProperties(properties);
        // 放入到map中
        launcherMap.put(registerCodeLauncher.getId(), registerCodeLauncher);
    }



}
